﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys;
using HamcoWcs.Models.Common;
using HamcoWcs.Models.Exceptions;
using HamcoWcs.Models.MaintainRecords;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;

namespace HamcoWcs.Main.Controllers.Common
{
    /// <summary>
    /// 保养控制器
    /// </summary>
    public class MaintainController : BasicController
    {
        public MaintainController(ILoggerService logger, IMapper mapper, WcsDbContext wcsDbContext) : base(logger, mapper, wcsDbContext)
        {
        }

        public override string ControllerName => "MaintainController";

        /// <summary>
        /// 新增保养记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(MaintainRecordAddModel model, [FromHeader] string userName = "UNK")
        {
            try
            {
                if (model is null) throw new WarningException("参数异常");
                if (string.IsNullOrEmpty(model.Content)) throw new WarningException("参数异常：保养内容");
                if (string.IsNullOrEmpty(model.UnderTaker)) throw new WarningException("参数异常：维保人员");
                if (string.IsNullOrEmpty(model.MachineName)) throw new WarningException("参数异常：机台名");
                if (model.MachineName == default) throw new WarningException("参数异常：维保日期");

                var record = new MaintainRecord()
                {
                    Content = model.Content,
                    MachineName = model.MachineName,
                    UnderTaker = model.UnderTaker,
                    MaintainTime = model.MaintainTime,
                };
                _wcsDbContext.Set<MaintainRecord>().Add(record);
                _wcsDbContext.SaveChanges();
                AddOperationLog(userName, $"添加了一条维保信息", "", model.MachineName);

                return Json(ForeEndResult.Ok);
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return CreateFailureResult();
            }
        }


        /// <summary>
        /// 删除保养记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Delete(BaseModel model, [FromHeader] string userName)
        {
            try
            {
                if (model is null || model.Id == 0) throw new WarningException("参数异常");

                var record = _wcsDbContext.Set<MaintainRecord>().FirstOrDefault(x => x.Id == model.Id)
                ?? throw new WarningException("s");

                _wcsDbContext.Set<MaintainRecord>().Remove(record);
                _wcsDbContext.SaveChanges();

                AddOperationLog(userName, $"删除了一条维保信息 [id:{model.Id}]", "", record.MachineName);

                return Json(ForeEndResult.Ok, DEFAULT_JSON_SETTINGS);
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return DeleteFailureResult();
            }
        }


        /// <summary>
        /// 修改保养记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Update(MaintainRecordUpdateModel model, [FromHeader] string userName)
        {
            try
            {
                /* 1传入参数检查 */
                /* 2修改逻辑 */
                if (model is null) throw new WarningException("参数异常");
                if (string.IsNullOrEmpty(model.Content)) throw new WarningException("参数异常：保养内容");
                if (string.IsNullOrEmpty(model.UnderTaker)) throw new WarningException("参数异常：维保人员");
                if (string.IsNullOrEmpty(model.MachineName)) throw new WarningException("参数异常：机台名");
                if (model.MachineName == default) throw new WarningException("参数异常：维保日期");

                var record = _wcsDbContext.Set<MaintainRecord>().FirstOrDefault(x => x.Id == model.Id)
                    ?? throw new WarningException("未找到要修改的维保信息");

                record.Content = model.Content;
                record.MachineName = model.MachineName;
                record.UnderTaker = model.UnderTaker;
                record.MaintainTime = model.MaintainTime;
                _wcsDbContext.SaveChanges();
                //return Json(ForeEndResult.Ok, DEFAULT_JSON_SETTINGS);
                AddOperationLog(userName, $"编辑了一条维保信息 [id:{model.Id}]", "", model.MachineName);
                return Json(ForeEndResult.Ok);

            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return DeleteFailureResult();
            }
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPost]
        public IActionResult Pagion(MaintainRecordQueryModel model)
        {
            try
            {
                var data = _wcsDbContext.Set<MaintainRecord>().AsQueryable()
                     .AsNoTracking()
                     .WhereIf(x => x.UnderTaker.Contains(model.UnderTaker), !string.IsNullOrEmpty(model.UnderTaker))
                     .WhereIf(x => x.MachineName.Contains(model.MachineName), !string.IsNullOrEmpty(model.MachineName))
                     .WhereIf(x => x.MaintainTime >= model.StartTime, model.StartTime != default)
                     .WhereIf(x => x.MaintainTime <= model.EndTime, model.EndTime != default)
                     .Pagion(model.Page, model.Size, out int count, out int pageCount)
                     .ToList();

                return Json(new ForeEndResult(data, count, pageCount));
            }
            catch (WarningException ex)
            {
                return Warning(ex);
            }
            catch (Exception ex)
            {
                AddSystemLog(ex.Message);
                return QueryFailureResult();
            }
        }


    }
}
